package com.pie4cloud.pie.dmz.handler;

import com.pie4cloud.pie.dmz.entty.constant.ConstantValue;
import com.pie4cloud.pie.dmz.entty.netty.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.CharsetUtil;

public class MsgEncoder extends MessageToByteEncoder<Message> {
	@Override
	protected void encode(ChannelHandlerContext channelHandlerContext, Message message, ByteBuf byteBuf) throws Exception {

		byteBuf.writeInt(ConstantValue.MSG_HEAD);
		byteBuf.writeInt(message.getSessionId().length());
		byteBuf.writeCharSequence(message.getSessionId(), CharsetUtil.UTF_8);
		byteBuf.writeInt(message.getMsgTypeEnum().getType());
		if (message.getMsgBody() == null) {
			byteBuf.writeInt(0);
		} else {
			byteBuf.writeInt(message.getMsgLength());
			byteBuf.writeBytes(message.getMsgBody());
		}
	}
}
